﻿using Commonality.Common;
using Commonality.ReturnView;
using Commonality.ServerEnum;
using IService.Managemen;
using Microsoft.AspNetCore.Mvc.Rendering;
using Models.Managemen;
using ModelToDto.Managemen;
using SqlSugar;
using System.Linq.Expressions;
using System.Security.Claims;

namespace Service.Managemen
{

    public class UserService : BaseService, IUserService
    {
        ISqlSugarClient _sqlSugarClient { get; set; }

        public UserService(ISqlSugarClient SqlSugarClient) : base(SqlSugarClient)
        {
            _sqlSugarClient = SqlSugarClient;
        }

        public async Task<UserRoleDTO> GetUserRole(int userId)
        {
            Expressionable<Mp_UserRole> expression = Expressionable.Create<Mp_UserRole>();
            expression.And(t => t.UserId == userId);

            var userRolelChck = await FindQueryForWhere(expression.ToExpression());
            var roleIds = userRolelChck.Select(t => t.UserId).ToArray();
            //注意状态筛选
            var roleOrUserRoles = sqlSugarClient.Queryable<Mp_Role>().Where(t => t.Status == (int)UserStatuEnum.Normal).Select(t => new SelectListItem
            {
                Selected = roleIds.Contains(t.RoleId),
                Text = t.Text,
                Value = t.RoleId.ToString()
            });
            var user = IFindEntityForID<Mp_Users>(userId);

            return new UserRoleDTO
            {
                UserID = user.UserId,
                UserName = user.Name,
                selectListItems = roleOrUserRoles.ToList()
            };
        }

        public async Task<int> AssignRolesAdd(int userId, List<string> roleList)
        {
            List<Mp_UserRole> userRole = new List<Mp_UserRole>();
            foreach (var item in roleList)
            {
                userRole.Add(new Mp_UserRole
                {
                    UserId = userId,
                    RoleId = Convert.ToInt32(item)
                });
            }
            try
            {
                sqlSugarClient.Ado.BeginTran();
                await sqlSugarClient.Deleteable<Mp_UserRole>().Where(t => t.UserId == userId).ExecuteCommandAsync();
                await InsertList(userRole);
                sqlSugarClient.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {

                return 0;
            }
        }

        public Mp_Users LoginUser(LoginUserDTO loginUserDTO)
        {
            var md5Pwd = Common.Encrypt(loginUserDTO.Password);
            var user = sqlSugarClient.Queryable<Mp_Users>().Where(t => t.Name == loginUserDTO.Name && t.Password == md5Pwd).First();

            return user;
        }
    }

}